package controller

import (
	"github.com/google/uuid"
	"log"
	config2 "passwordBook/config"
	"passwordBook/entity"
	"passwordBook/sql"
	"time"
)

type PwBookController struct {
	BasicController
}
type pwBookMsg struct {
	Name              string `json:"name"`
	EncryptMethod     string `json:"encryptMethod"`
	PrivateKeyPath    string `json:"privateKeyPath"`
	PublicKeyFilePath string `json:"publicKeyFilePath"`
	EncryptKey        string `json:"encryptKey"`
}

func (p *PwBookController) Create() {
	pBook := pwBookMsg{}
	p.BindJSON(&pBook)
	uuid := uuid.New()
	time := time.Now()
	config := config2.BookConfig{EncryptMethod: pBook.EncryptMethod, PublicKeyFilePath: pBook.PublicKeyFilePath,
		PrivateKeyFilePath: pBook.PrivateKeyPath, EncryptKey: pBook.EncryptKey}
	book := entity.PwBook{Id: uuid.String(), Name: pBook.Name, CreateTime: time, Config: config}
	log.Printf("创建新的密码本——%s，加密方式：%s \n", book.Name, book.Config.EncryptMethod)
	sql.GLOBAL_DB.Db.Create(&book)
	p.Message = Message{Code: 200, Msg: "创建成功", Data: book}
	log.Println(p.Message)
	p.JSONResp(p.Message)

}
func (p *PwBookController) List() {
	var books []entity.PwBook
	sql.GLOBAL_DB.Db.Find(&books)
	p.Message = Message{Code: 200, Msg: "查询成功", Data: books}
	p.JSONResp(p.Message)

}

func (p *PwBookController) Delete() {
	id := p.Ctx.Input.Param(":id")
	log.Println("删除密码本：" + id)
	sql.GLOBAL_DB.Db.Delete(&entity.PwBook{Id: id})
	p.Message = Message{Code: 200, Msg: "删除成功"}
	p.JSONResp(p.Message)
}
func (p *PwBookController) Edit() {
	var book entity.PwBook
	p.BindJSON(&book)
	log.Println("修改密码本：" + book.Id)
	book.UpdateTime = time.Now()
	sql.GLOBAL_DB.Db.Updates(&book)
	sql.GLOBAL_DB.Db.Find(&book)
	p.Message = Message{Code: 200, Msg: "更新成功", Data: book}
	p.JSONResp(p.Message)
}
